/*
 * @Author: Your name
 * @Date:   2020-07-07 10:35:29
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-07-07 10:35:29
 */
/* 
    模拟express框架
    目前我们封装想要实现的效果是：
        app.get('login', function(req, res){
            res.send();
        })
*/
//定义一个全局的对象用来挂载方法
const url = require("url");
const fs = require("fs");
const path = require("path");


//封装类似express框架中的send方法
let changeRes = (res) => {
  res.send = (data) => {
    res.writeHead(200, { "Content-Type": 'text/html;charset="utf-8"' });
    res.end(data);
  }; 
};


//根据后缀名获取文件类型
let getMine = function (extendName) {
  let data = fs.readFileSync("./data/mime.json");
  return JSON.parse(data.toString())[extendName];
};


//静态web服务的方法
let initStatic = function (req, res, staticName) {
  //获取url地址
  let pathName = url.parse(req.url).pathname;
  pathName = pathName === "/" ? "/index.html" : pathName;
  //获取后缀名
  let extName = path.extname(pathName);
  try {
    let data = fs.readFileSync("./" + staticName + pathName);
    let mime = getMine(extName);
    console.log(mime);
    res.writeHead(200, { "Content-Type": mime + ';charset="utf-8"' });
    res.end(data);
  } catch (error) {}
};

let server = function () {
  let G = {
    _get: {}, //专门挂载get方法的路由
    _post: {}, //专门挂载post方法的路由
    staticPath: "public", //默认的静态web目录
  };

  let app = function (req, res) {
    //扩展res的方法
    changeRes(res);
    //配置静态web服务
    initStatic(req, res, G.staticPath); //匹配不到的话向下匹配
    
    let pathName = url.parse(req.url).pathname;
    let method = req.method.toLowerCase();
    if (G["_" + method][pathName]) {
      if (method === "get") {
        G["_get"][pathName](req, res);
      } else if (method === "post") {
        //获取post表单数据
        let postData = "";
        req.on("data", (chunk) => {
          postData += chunk;
        });
        req.on("end", () => {
          req.body = postData;
          G["_post"][pathName](req, res);
        });
      }
    } else {
      res.writeHead(404, { "Content-Type": 'text/html;charset="utf-8"' });
      res.end("<h1>404 is not found</h1>");
    }
  };

  //配置get请求
  app.get = function (str, callback) {
    G["_get"][str] = callback;
  };
  //配置post请求
  app.post = function (str, callback) {
    //get和post方法不能都混起来放在G中，如果请求方法不同但是str相同，会覆盖掉上面的方法
    G["_post"][str] = callback;
  };
  //配置静态web服务的目录
  app.static = function (staticPath) {
    G.staticPath = staticPath;
  };
  console.log(G.staticPath);
  return app;
};

module.exports = server();
